package question6_10;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;

/**
 * @description:  用两个队列模拟栈
 * @author: jhy
 * @time: 2021/5/19 17:03
 */
public class Question9_2 {

    public static void main(String[] args) {

        Question9_2 question9_2 = new Question9_2();
        question9_2.push(1);
        question9_2.push(2);
        question9_2.push(3);
        System.out.println(question9_2.pop());
        System.out.println(question9_2.pop());
        System.out.println(question9_2.pop());

    }

    //两个队列模拟栈
    Queue<Integer> queue1 = new ArrayDeque();
    Queue<Integer> queue2 = new ArrayDeque();

    //入栈
    public void push(int val){
        //入栈时，哪个队列有元素，加入哪个队列
        if(queue1.isEmpty()){
            queue2.offer(val);
        }else {
            queue1.offer(val);
        }
    }

    //出栈
    public int pop(){
        //将有值的队列，依次出队，加入到没有值的队列
        if(!queue1.isEmpty()){
            while (queue1.size() > 1){
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }else if(!queue2.isEmpty()){
            while (queue2.size() > 1){
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }

        return -1;
    }
}
